#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys, datetime
import calendar
import datetime as dt
from dateutil.relativedelta import relativedelta


class XDateTimeUtils(object):

    @staticmethod
    def advance(p_datetime, p_years=0, p_months=0, p_days=0, p_hours=0, p_minutes=0, p_seconds=0):
        """

        :param p_datetime:
        :param p_years:
        :param p_months:
        :param p_days:
        :param p_hours:
        :param p_minutes:
        :param p_seconds:
        :return:
        """
        ret = p_datetime + relativedelta(years=p_years, months=p_months, days=p_days, hours=p_hours, minutes=p_minutes,
                                         seconds=p_seconds)
        return ret


    """
    This module contains boilerplate datetime helpers.

    ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    """

    # @staticmethod
    # def advance_days(p_timestamp=None, p_format='%Y%m%d%H%M%S', p_day=0):
    #     t_a = datetime.datetime.strptime(str(p_timestamp), p_format)
    #     t = (t_a + datetime.timedelta(days=p_day)).strftime(p_format)
    #     return t
    #
    # @staticmethod
    # def advance(p_timestamp=None, p_format='%Y%m%d%H%M%S', p_days=0, p_hours=0, p_minutes=0, p_seconds=0):
    #     t_a = datetime.datetime.strptime(str(p_timestamp), p_format)
    #     t = (t_a + datetime.timedelta(days=p_days, hours=p_hours, minutes=p_minutes, seconds=p_seconds)).strftime(
    #         p_format)
    #     return t

    @staticmethod
    def iso8601_to_datetime(p_str_time=None):
        """
        Convert ISO 8601 strings to datetime instance.
        """
        try:
            return dt.datetime.strptime(p_str_time, "%Y-%m-%dT%H:%M:%S.%fZ")
        except ValueError:
            return dt.datetime.strptime(p_str_time, "%Y-%m-%dT%H:%M:%SZ")

    @staticmethod
    def datetime_to_iso8601(p_datetime=datetime.datetime.now()):
        """
        Convert p_datetime to ISO 8601 string.
        """
        if p_datetime.microsecond > 0:
            return p_datetime.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        return p_datetime.strftime("%Y-%m-%dT%H:%M:%SZ")

    @staticmethod
    def date_to_iso8601(p_date=None):
        """
        Convert p_date to ISO 8601 string.
        """
        mydt = datetime.datetime.combine(p_date, datetime.datetime.min.time())
        if mydt.microsecond > 0:
            return mydt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        return mydt.strftime("%Y-%m-%dT%H:%M:%SZ")

    @staticmethod
    def datetime_to_unixtimestamp(p_datetime=datetime.datetime.now()):
        """
        Convert p_datetime to Unix timestamp.
        """
        return int(calendar.timegm(p_datetime.timetuple()))
